package com.example.springbootsenior.ThreadPool;

import com.example.springbootsenior.SpringBootSeniorApplication;
import com.example.springbootsenior.ThreadPool.config.AsyncTaskConfig;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

/**
 * <pre>
 * 功能描述:SpringBoot+线程池+异步回调
 * 整合视频 ：https://www.bilibili.com/video/BV1kb4y1b75q?from=search&seid=5366133170492591623&spm_id_from=333.337.0.0
 *
 * </pre>
 *
 * @author: 李明杰
 * @date: 2022/1/20 15:47
 */
@SpringBootTest(classes = {SpringBootSeniorApplication.class})
@Slf4j
public class UseThreadPool {
    @Resource//线程池哪里使用就放在哪里
    private ThreadPoolTaskExecutor executorService;

    @Resource//打印线程池配置
    private AsyncTaskConfig asyncTaskConfig;


    /**
     * 线程池基本使用
     *
     * @throws Exception
     */
    @Test
    public void exeTask() throws Exception {

        System.err.println("asyncTask(10) = " + asyncTask(10));//打印返回结果集合
        System.err.println(asyncTaskConfig);//打印线程池配置

    }

    /**
     * 线程池的基本使用
     *
     * @param i
     * @return
     * @throws Exception
     */
    @Async("taskExecutor")
    public List asyncTask(int i) throws Exception {
        ArrayList<String> list = new ArrayList<>();
        for (int j = 0; j < i; j++) {

            int finalJ = j;
//            submit与execute区别：
            Future<String> submit = executorService.submit(() -> {
                log.info(Thread.currentThread().getName());
                return "finish" + finalJ;
            });
            System.out.println("submit.get() = " + submit.get());
            list.add(submit.get());
        }
        return list;
    }


}
